﻿package plugins.yzhkof.pv3d.view
{
    import core.manager.*;
    import core.manager.popupManager.CustomPopupManager;
    import core.manager.sceneManager.*;
    
    import flash.display.*;
    import flash.events.*;
    import flash.filters.*;
    import flash.geom.*;
    import flash.net.*;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;
    
    import gs.*;
    
    import loaders.*;
    
    import memory.*;
    
    import movement.*;
    
    import mx.core.*;
    
    import org.papervision3d.cameras.*;
    import org.papervision3d.core.proto.*;
    import org.papervision3d.events.*;
    import org.papervision3d.materials.*;
    import org.papervision3d.objects.primitives.*;
    import org.papervision3d.render.*;
    import org.papervision3d.scenes.*;
    import org.papervision3d.view.*;
    import org.papervision3d.view.stats.*;
    
    import plugins.yzhkof.view.*;
    
    import pv3d.*;
    
    import view.*;
    import view.fl2mx.*;
    
    import yzhkof.*;

    public class Pv3d360Scene extends Sprite
    {
        protected const LOADING_IMG:String = "LOADING_IMG";
        protected var url_type:String;
        private var compassBitmapdata:BitmapData;
        protected var scene:Scene3D;
        protected var pheight:Number;
        public var arrows:Array;
        private var this_stage:Stage;
        protected var state:String;
        protected var pLoader:Loader;
        private var movements:Array;
        public var camera:FreeCamera3D;
        protected var viewport:Viewport3D;
        protected var material:MaterialObject3D;
        protected const INITING:String = "INITING";
        protected var czoom:Number;
        protected var onComplete:Function;
        public var animates:Array;
        protected var pdetail:Number;
        protected var renderer:BasicRenderEngine;
        private var stats_view:StatsView;
        protected const BROWSING:String = "BROWSING";
        protected var sphere:Sphere;
        private var arrow_bitmapdata:BitmapData;
        protected var pwidth:Number;
        private var controlAble:Boolean = false;
        public var render_type:String = "REND_ALL";
        protected var tip_sprite:MapToolTip;
        protected var view_loader:LoadingLine;
        protected var compass_plane:Plane;
        private var addonLoader:SerialCacheMovieClipLoader;
        private var URLpath:URLRequest;
        private var distance:int = 10;
        protected var renderable:Boolean = false;
        public static const REND_ANIMATE:String = "REND_ANIMATE";
        public static const REND_ALL:String = "REND_ALL";
        private static var cacheShpereBitmap:BitmapData;

        public function Pv3d360Scene(pdetail:Number = 11, czoom:Number = 50)
        {
            compassBitmapdata = ToolBitmapData.getInstance().drawDisplayObject(new CompassSkin());
            arrow_bitmapdata = ToolBitmapData.getInstance().drawDisplayObject(new ArrowSkin());
            tip_sprite = new MapToolTip();
            state = INITING;
            animates = new Array();
            arrows = new Array();
            movements = new Array();
            addonLoader = new SerialCacheMovieClipLoader();
            this.pdetail = pdetail;
            this.czoom =czoom ;
            init();
            initListener();
            return;
        }// end function

        private function addToStageHandler(distance:Event) : void
        {
            this_stage = this.stage;
            this_stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true);
            this_stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, false, 0, true);
            return;
        }// end function

        public function cleanAllAddon() : void
        {
            BitmapMaterialAddonManager.getInstance().removeAllAddon();
            return;
        }// end function

        protected function init() : void
        {
            renderer = new BasicRenderEngine();
            scene = new Scene3D();
            camera = new FreeCamera3D();
            camera.focus = 375;
            viewport = new Viewport3D(900, 600, false, true);
            pLoader = new Loader();
            pLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, chageCompleteHandler);
            pLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgessHandler);
            addChild(viewport);
            camera.z = 1;
            sphere = new Sphere(material, 5000, 40, 20);
            sphere.scaleX = sphere.scaleX * -1;
            var _loc_1:* = new BitmapMaterial(compassBitmapdata.clone());
            _loc_1.doubleSided = true;
            compass_plane = new Plane(_loc_1, 75, 75, 5, 5);
            compass_plane.rotationX = -90;
            compass_plane.y = -80;
            compass_plane.z = 1;
            scene.addChild(compass_plane);
            scene.addChild(sphere);
            state = BROWSING;
            return;
        }// end function

        public function addArrow(destination:int,rota:Number=0, tip_text:String="",tip_english:String=" ") : Plane
        {
            var plane:Plane;
            var glowFilter:GlowFilter;
            var material_arrow:* = new BitmapMaterial(arrow_bitmapdata.clone());
            material_arrow.smooth = true;
            material_arrow.doubleSided = true;
            material_arrow.interactive = true;
            plane = new Plane(material_arrow, 4.2, 25.2, 2, 4);
            arrows.push(plane);
            plane.rotationX = -90;
            plane.rotationY = rota;
            plane.moveUp(14);
            plane.y = -80;
            scene.addChild(plane);
            plane.useOwnContainer = true;
            glowFilter = new GlowFilter(85, 1, 16, 16, 2, 1, false, false);
            if (tip_text.length > 0)
            {
                plane.extra = {textEnglish:tip_english,text:tip_text};
                plane.addEventListener(InteractiveScene3DEvent.OBJECT_OVER, function (distance:Event) : void
            {
                addChild(tip_sprite);
                if(MainSystemProperty.LANGUAGE==MainSystemProperty.CHINESE)
                {
                	tip_sprite.text = distance.currentTarget.extra.text;
                }else
                {
                	tip_sprite.text = distance.currentTarget.extra.textEnglish;
                }
                plane.filters = [glowFilter];
                return;
            }// end function
            );
                plane.addEventListener(InteractiveScene3DEvent.OBJECT_OUT, function (distance:Event) : void
            {
                removeChild(tip_sprite);
                plane.filters = [];
                return;
            }// end function
            );
                plane.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, function (distance:InteractiveScene3DEvent) : void
            {
                SceneManager.getInstance().gotoScene(destination);
                return;
            }// end function
            );
            }
            draw();
            return plane;
        }// end function

        public function removeAllObject() : void
        {
            this.cleanAllArrow();
            this.cleanAllAnimate();
            this.cleanAllAddon();
            MyGC.gc();
            return;
        }// end function

        public function cleanAllAnimate() : void
        {
            var _loc_1:UpDownMovement;
            var _loc_2:Plane;
            if (movements.length > 0)
            {
                for each (_loc_1 in movements)
                {
                    
                    _loc_1.dispose();
                    _loc_1 = null;
                }
            }
            if (animates.length > 0)
            {
                for each (_loc_2 in animates)
                {
                    
                    if (_loc_2.parent != null)
                    {
                        _loc_2.parent.removeChild(_loc_2);
                    }
                    if (_loc_2.material != null)
                    {
                        if (_loc_2.material.bitmap != null)
                        {
                            _loc_2.material.bitmap.dispose();
                        }
                        _loc_2.material.destroy();
                    }
                    _loc_2 = null;
                }
                animates = new Array();
            }
            return;
        }// end function

        public function startRend() : void
        {
            controlAble = true;
            renderable = true;
            BitmapMaterialAddonManager.getInstance().startAll();
            return;
        }// end function

        public function addAminate(URL:String, init_obj:Object, cache:Boolean=false) : Plane
        {
            var plane_animate:BendPlane;
            var autoKeep:Number;
            var rotateSpeed:int;
            var scaleSpeed:Number;
            var m:UpDownMovement;
            var glowFilter:GlowFilter;
			var width:Number=init_obj["width"] ? init_obj["width"] : 100;
			var height:Number=init_obj["height"] ? init_obj["height"] : 100;
			var segmentsW:Number=init_obj["segmentsW"] ? init_obj["segmentsW"] : 2;
			var segmentsH:Number=init_obj["segmentsH"] ? init_obj["segmentsH"] : 2;
			var visible:Number=init_obj["visible"] ? init_obj["visible"] : 1;
			var tip:String=init_obj["tip"] ? init_obj["tip"] : "";
			var englishTip:String=init_obj["tipEnglish"] ? init_obj["tipEnglish"] : "";
			var movement:int=init_obj["movement"] ? init_obj["movement"] : 0;
			var maxHeight:Number=init_obj["maxHeight"] ? init_obj["maxHeight"] : 0;
			var minHeight:Number=init_obj["minHeight"] ? init_obj["minHeight"] : 0;
			var speed:Number=init_obj["speed"] ? init_obj["speed"] : 0;
			var filter:int=init_obj["filter"] ? init_obj["filter"] : 0;
			var sign:int=init_obj["sign"] ? init_obj["sign"] : 0;
			var debuge:int=init_obj["debuge"] ? init_obj["debuge"] : 0;
            plane_animate = new BendPlane(new ColorMaterial(16777215, 0), width, height, segmentsW, segmentsH, init_obj);
            plane_animate.offset = init_obj["offset"] ? (init_obj["offset"]) : (0);
            plane_animate.angle = init_obj["angle"] ? (init_obj["angle"]) : (0);
            plane_animate.force = init_obj["force"] ? (init_obj["force"]) : (0);
            autoKeep = init_obj["autoKeep"] ? (init_obj["autoKeep"]) : (0);
            if (Number(init_obj["scaleX"]) == 0 || Number(init_obj["scaleX"]) < 0)
            {
                plane_animate.scaleX = 1;
            }
            else
            {
                plane_animate.scaleX = Number(init_obj["scaleX"]);
            }
            if (Number(init_obj["scaleY"]) == 0 || Number(init_obj["scaleY"]) < 0)
            {
                plane_animate.scaleY = 1;
            }
            else
            {
                plane_animate.scaleY = Number(init_obj["scaleY"]);
            }
            plane_animate.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, function (distance:InteractiveScene3DEvent) : void
            {
                MainSystem.getInstance().runScript(init_obj["onClick"]);
                if (sign == 1)
                {
                    plane_animate.alpha = 0.5;
                }
                if (autoKeep == 1)
                {
                    plane_animate.material.interactive = false;
                }
                return;
            }// end function
            );
            if (movement == 1)
            {
                m = new UpDownMovement(plane_animate, maxHeight, minHeight, speed);
                movements.push(m);
            }
            animates.push(plane_animate);
            scene.addChild(plane_animate);
            var loader:* = new Loader();
            var context:LoaderContext=new LoaderContext(false,ApplicationDomain.currentDomain);
            loader.load(new URLRequest(URL),context);
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function (distance:Event) : void
            {
                var _loc_2:MovieClip;
                var _loc_3:MovieMaterial;
                var _loc_4:ColorMaterial;
                if (animates.indexOf(plane_animate) > -1)
                {
                    _loc_2 = distance.currentTarget.content;
                    if (visible == 1)
                    {
                        if (cache)
                        {
                            _loc_3 = new MovieCacheMaterial(_loc_2, true, true, true, new Rectangle(0, 0, _loc_2.width, _loc_2.height));
                        }
                        else
                        {
                            _loc_3 = new MovieMaterial(_loc_2, true, true, true, new Rectangle(0, 0, _loc_2.width, _loc_2.height));
                        }
                        _loc_3.allowAutoResize = false;
                        _loc_3.smooth = true;
                        _loc_3.interactive = true;
                        plane_animate.material = _loc_3;
                    }
                    else
                    {
                        _loc_4 = new ColorMaterial(10994976, 0);
                        _loc_4.doubleSided = true;
                        _loc_4.interactive = true;
                        plane_animate.material = _loc_4;
                    }
                }
                return;
            }// end function
            );
            if (filter == 1)
            {
                glowFilter = new GlowFilter(39168, 1, 16, 16, 1, 1, false, false);
                plane_animate.useOwnContainer = true;
            }
            plane_animate.addEventListener(InteractiveScene3DEvent.OBJECT_OVER, function (distance:InteractiveScene3DEvent) : void
            {
            	if(MainSystemProperty.LANGUAGE==MainSystemProperty.CHINESE)
            	{
	                if (tip != "")
	                {
	                    tip_sprite.text = tip;
	                    addChild(tip_sprite);
	                }
            	}else
            	{
	                if (englishTip != "")
	                {
	                    tip_sprite.text = englishTip;
	                    addChild(tip_sprite);
	                }
            	}
            	if(!CustomPopupManager.getInstance().isPop)
            	{
	                plane_animate.filters = [glowFilter];
	                MainSystem.getInstance().runScript(init_obj["onOver"]);
            	}
            }// end function
            );
            plane_animate.addEventListener(InteractiveScene3DEvent.OBJECT_OUT, function (distance:InteractiveScene3DEvent) : void
            {
                if (tip_sprite!=null && tip_sprite.parent!=null)
                {
                    tip_sprite.parent.removeChild(tip_sprite);
                }
                plane_animate.filters = [];
                MainSystem.getInstance().runScript(init_obj["onOut"]);
                return;
            }// end function
            );
            rotateSpeed;
            scaleSpeed;
            if (debuge == 1)
            {
                Application.application.stage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent) : void
            {
                if (e.keyCode == 87)
                {
                    plane_animate.z = plane_animate.z + distance;
                }
                if (e.keyCode == 83)
                {
                    plane_animate.z = plane_animate.z - distance;
                }
                if (e.keyCode == 65)
                {
                    plane_animate.x = plane_animate.x + distance;
                }
                if (e.keyCode == 68)
                {
                    plane_animate.x = plane_animate.x - distance;
                }
                if (e.keyCode == 189)
                {
                    plane_animate.y = plane_animate.y + distance;
                }
                if (e.keyCode == 187)
                {
                    plane_animate.y = plane_animate.y - distance;
                }
                if (e.keyCode == 81)
                {
                    plane_animate.rotationY = plane_animate.rotationY + rotateSpeed;
                }
                if (e.keyCode == 69)
                {
                    plane_animate.rotationY = plane_animate.rotationY - rotateSpeed;
                }
                if (e.keyCode == 90)
                {
                    plane_animate.scaleX = plane_animate.scaleX + scaleSpeed;
                }
                if (e.keyCode == 88)
                {
                    plane_animate.scaleX = plane_animate.scaleX - scaleSpeed;
                }
                if (e.keyCode == 67)
                {
                    plane_animate.scaleY = plane_animate.scaleY + scaleSpeed;
                }
                if (e.keyCode == 86)
                {
                    plane_animate.scaleY = plane_animate.scaleY - scaleSpeed;
                }
                if (e.keyCode == 73)
                {
                    distance = distance + 10;
                }
                if (e.keyCode == 75)
                {
                    distance = distance - 10;
                }
                trace("x=\"" + plane_animate.x + "\" y=\"" + plane_animate.y + "\" z=\"" + plane_animate.z + "\" rotationY=\"" + plane_animate.rotationY + "\"" + " scaleX=\"" + plane_animate.scaleX + "\" scaleY=\"" + plane_animate.scaleY + "\"");
                return;
            }// end function
            );
            }
            return plane_animate;
        }// end function

        public function draw() : void
        {
            if (tip_sprite != null)
            {
                tip_sprite.x = mouseX;
                tip_sprite.y = mouseY;
            }
            renderer.renderScene(scene, camera, viewport);
            return;
        }// end function

        public function stopRend() : void
        {
            controlAble = false;
            renderable = false;
            BitmapMaterialAddonManager.getInstance().stopAll();
            return;
        }// end function

        public function cleanAllArrow() : void
        {
            var _loc_1:Plane;
            if (arrows.length > 0)
            {
                for each (_loc_1 in arrows)
                {
                    
                    if (_loc_1.parent != null)
                    {
                        _loc_1.parent.removeChild(_loc_1);
                    }
                    if (_loc_1.material != null)
                    {
                        if (_loc_1.material.bitmap != null)
                        {
                            _loc_1.material.bitmap.dispose();
                        }
                        _loc_1.material.destroy();
                    }
                    _loc_1 = null;
                }
                arrows = new Array();
            }
            return;
        }// end function

        private function mouseMoveHandler(distance:MouseEvent) : void
        {
            if (controlAble)
            {
                renderable = true;
            }
            return;
        }// end function

        private function mouseLeaveHandler(distance:Event) : void
        {
            renderable = false;
            return;
        }// end function

        public function updateAddons(distance:XMLList) : void
        {
            distance = distance;
            var _loc_2:int;
            while (_loc_2 < distance.length())
            {
                
                BitmapMaterialAddonManager.getInstance().addAddon(material, distance[_loc_2].@url, distance[_loc_2].@url, {x:distance[_loc_2].@x, y:distance[_loc_2].@y, scaleX:distance[_loc_2].@scaleX, scaleY:distance[_loc_2].@scaleY, rotation:distance[_loc_2].@rotation});
                _loc_2++;
            }
            return;
        }// end function

        private function loadProgessHandler(distance:ProgressEvent) : void
        {
            view_loader.percent_text.text = Math.round(distance.bytesLoaded / distance.bytesTotal * 100) + "%";
            return;
        }// end function

        private function loadEnterFrameHandler(distance:Event) : void
        {
            if (distance.currentTarget != null && this_stage != null)
            {
                distance.currentTarget.x = this_stage.mouseX;
                distance.currentTarget.y = this_stage.mouseY;
            }
            return;
        }// end function

        public function setCompassRotation(distance:Number) : void
        {
            compass_plane.rotationY = distance;
            return;
        }// end function

        private function onEnterFrameHandler(distance:Event) : void
        {
            if (renderable)
            {
                draw();
            }
            return;
        }// end function

        private function initListener() : void
        {
            addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
            addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
            return;
        }// end function

        protected function chageCompleteHandler(distance:Event) : void
        {
            var e:* = distance;
            TweenLite.to(view_loader, 0.5, {alpha:0, onCompleteParams:[view_loader], onComplete:function (... args) : void
            {
                view_loader.removeEventListener(Event.ENTER_FRAME, loadEnterFrameHandler);
                if (view_loader.parent != null)
                {
                    view_loader.parent.removeChild(view_loader);
                }
                view_loader = null;
                return;
            }// end function
            });
            if (material != null && material.bitmap != null)
            {
                material.bitmap = null;
                material.destroy();
                material = null;
            }
            if (sphere.material != null)
            {
                sphere.material = null;
            }
            if (cacheShpereBitmap != null)
            {
                cacheShpereBitmap.dispose();
                cacheShpereBitmap = null;
            }
            switch(url_type)
            {
                case "movieclip":
                {
                    material = new MovieMaterial(MovieClip(pLoader.content), true, true, true);
                    break;
                }
                default:
                {
                    cacheShpereBitmap = Bitmap(pLoader.content).bitmapData;
                    pLoader.unload();
                    material = new BitmapMaterial(cacheShpereBitmap, true);
                    break;
                    break;
                }
            }
            material.doubleSided = false;
            material.smooth = true;
            material.interactive = false;
            sphere.material = material;
            MyGC.gc();
            onComplete();
            state = BROWSING;
            return;
        }// end function

        public function changeBitmap(url:String, url_type:String = "", onComplete:Function = null) : void
        {
            if (state != LOADING_IMG)
            {
                state = LOADING_IMG;
                this.url_type = url_type;
                this.onComplete = onComplete;
                if (view_loader != null)
                {
                    view_loader.removeEventListener(Event.ENTER_FRAME, loadEnterFrameHandler);
                }
                view_loader = new LoadingLine();
                view_loader.addEventListener(Event.ENTER_FRAME, loadEnterFrameHandler);
                view_loader.percent_text.text = "0%";
                view_loader.percent_text.selectable = false;
                Application.application.addChild(Fl2Mx.fl2Mx(view_loader));
                pLoader.load(new URLRequest(url));
            }
            return;
        }// end function

    }
}
